import { useTabsStore } from '@/store/modules/tabs'
import { decrypt } from '../utils/encrypt'

/**
 * 获取路由query
 * @param queryField query字段
 * @param isValid 是否验证
 * @param exclude 排除的验证
 * @param isEncrypt 是否加密
 * @returns
 */
export async function getRouteQuery<T extends Record<string, any>>(
  queryField: string[],
  {
    isValid = true,
    isEncrypt = false,
    exclude
  }: {
    isValid?: boolean
    isEncrypt?: boolean
    exclude?: string[]
  } = {}
) {
  const queryParams = {}
  const router = useRouter()
  const { path, query: _query } = router.currentRoute.value
  let query = _query || {}

  if (isEncrypt && _query?.query) {
    const queryString = decrypt(_query.query)
    query = JSON.parse(queryString) as any
  }
  let isOk = true

  if (queryField?.length) {
    if (isValid) {
      queryField.forEach((field) => {
        if (!query[field] && !exclude?.includes(field)) {
          isOk = false
        } else {
          queryParams[field] = query[field]
        }
      })
    } else {
      queryField.forEach((field) => {
        queryParams[field] = query[field]
      })
    }
  }
  if (!isOk) {
    const tabsStore = useTabsStore()
    tabsStore.delVisitedRoute(path)
    await router.push('/404')
  }

  return queryParams as T
}
